package ai.people.platform.information.listener;

import ai.people.core.plugin.annotation.HotRefresh;
import ai.people.platform.information.context.InformationServiceContext;
import ai.people.platform.information.timer.TimerSingletonHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 信息配置更改侦听器
 *
 * @author LiGuanNan
 * @date 2022/6/15 17:55
 */

@Slf4j
@HotRefresh
@Component("informationConfigChangeListener")
public class InformationConfigChangeListener implements ApplicationListener<EnvironmentChangeEvent> {

    @Autowired
    private InformationServiceContext informationServiceContext;

    @Override
    public void onApplicationEvent(EnvironmentChangeEvent environment) {
        Set<String> keys = environment.getKeys();
        if(keys.stream().anyMatch(o->o.contains("information.thirdparty.datasource"))){
            log.warn("检测到第三方数据源配置变更, 5s后刷新服务上下文， key:【{}】", keys);
            //延迟队列，5s后执行
            TimerSingletonHolder.getTimerInstance().newTimeout(timeout -> {
                informationServiceContext.refresh();
            }, 5, TimeUnit.SECONDS);
        }
    }
}